use crate::app::module::talker::Talker;
use crate::app::server::*;
use crate::app::module::rooms;
use crate::app::handle::errors;
use std::sync::mpsc::Sender;
use std::borrow::Borrow;


pub const GETROOMINFOLIST: u16 = 12001; //拉取房间信息
pub const JOINROOM: u16 = 12002; //拉取房间信息
pub const ROOMMSG: u16 = 12003; //向房间发送消息

pub struct HandleRoom {
}

impl handle::Handle for HandleRoom {
    fn handle(
        &self,
        client: &mut conn::ConnEntity,
        msg: message::Message,
    ) -> (bool, message::Message) {
        match msg.header {
            GETROOMINFOLIST =>{return (true,get_room_info_list());}
            JOINROOM =>{return (true,join_room(msg,client.sender.clone(),client))}
            ROOMMSG =>{return (true,room_msg(msg,client))}
            _ =>{}
        }
        (true, message::Message::new_null())
    }
}

pub fn get_room_info_list()->message::Message{
    let (list,ok) = rooms::get_room_info();
    if !ok{
        return errors::err_msg(500,"房间信息获取错误",GETROOMINFOLIST);
    }
    return errors::json_msg_log(&list,GETROOMINFOLIST);
}
pub fn join_room(msg:message::Message,sender:Sender<message::Message>,client:&mut conn::ConnEntity)->message::Message{
    let rid = msg.decode_body_to_u32() as u16;
    let talk = if let Some(o) = client.object.downcast_ref::<Talker>(){ o.clone() }else{
        return errors::err_msg(500,"客户信息为空",JOINROOM);
    };
    let room_detail = match rooms::join_room(rid,talk,sender){
        Err(e)=>{return  errors::err_msg(500,&e,JOINROOM);}
        Ok(o)=>{o}
    };
    if let Some(o) = client.object.downcast_mut::<Talker>(){
        o.room_id = rid;
    }
    return errors::json_msg_log(&room_detail,JOINROOM)
}
pub fn room_msg(msg:message::Message,client:&conn::ConnEntity)->message::Message {
    let rid = if let Some(o) = client.object.downcast_ref::<Talker>(){ o.room_id }else{
        return errors::err_msg(500,"客户信息为空",ROOMMSG);
    };
    if let Err(e) = rooms::send_room_msg(rid,msg){
        return errors::err_msg(500, e.borrow(), ROOMMSG)
    }
    return errors::string_msg_log("send success".to_string(),ROOMMSG)
}